package swc.smu.ui;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import swc.smu.adapter.MainPagerAdapter;
import swc.smu.adapter.MenuListAdapter;
import swc.smu.adapter.RecyclerAdapter;
import swc.smu.ui.custom.CircleImageView;

/**
 * Created by smu on 2016/1/27.
 */
public class CombinaActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener{

    ListView menuListView;
    MenuListAdapter menuListAdapter;

    ViewPager mViewPager;
    MainPagerAdapter mainPagerAdapter;
    static int[] PAGE_RESOURCE = {R.mipmap.p0, R.mipmap.p1,R.mipmap.p2, R.mipmap.p3};
    SwipeRefreshLayout mSwipeRefreshLayout;

    List<String> list;
    RecyclerView mRecyclerView;
    RecyclerAdapter mRecyclerAdapter;

    AppBarLayout appBarLayout;
    FloatingActionButton floatingActionButton;
    CollapsingToolbarLayout collapsingToolbarLayout;

    MyDrawerToggle toggle;
    DrawerLayout drawerLayout;

    static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    CombinaActivity activity = (CombinaActivity) msg.obj;
                    activity.mSwipeRefreshLayout.setRefreshing(false);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_combina);
        initToolbar();
        initData();
        initView();
        initViewAction();
    }

    /**
     * 初始化工具栏
     */
    public void initToolbar() {
        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);
        //设置Titlebar title 展开时title 位置
        collapsingToolbarLayout.setExpandedTitleGravity(Gravity.NO_GRAVITY);
        //设置Titlebar title 折叠后title 位置
        collapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER_HORIZONTAL);
        //设置Titlebar title 折叠后字体颜色
        collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);
        //设置Titlebar title 展开后字体颜色
        collapsingToolbarLayout.setExpandedTitleColor(Color.BLUE);
        //设置折叠后titlebar颜色
        collapsingToolbarLayout.setContentScrimColor(Color.parseColor("#99FF0000"));
        //设置title 是否可以被展开
        collapsingToolbarLayout.setTitleEnabled(true);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        //设置显示返回按钮 返回按钮的监听需在onOptionsItemSelected(MenuItem item) 方法中进行监听 返回按钮ID：android.R.id.home
        actionBar.setDisplayHomeAsUpEnabled(true);
        //设置是否显示titlebar title 默认为true 默认显示项目名称
        actionBar.setDisplayShowTitleEnabled(true);
        //自定义显示title内容
        actionBar.setTitle("松松");
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        drawerLayout.isDrawerOpen(menuListView);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        return super.onCreateOptionsMenu(menu);
        //设置自定义Menu
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /**
     * toolbar 中按钮选中监听
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home: //返回按钮
//                Toast.makeText(CombinaActivity.this, "I'm Clicked ", Toast.LENGTH_LONG).show();
                if (toggle.onOptionsItemSelected(item)) {
                    return true;
                }
                break;
            case  R.id.action_click:
//                Intent intent = new Intent("com.example.seat.TestActivity");
//                intent.setPackage("com.example.seat");
//                ComponentName componentName = new ComponentName("com.example.seat", "com.example.seat.TestActivity");
                try {
                    Intent intent = new Intent("com.example.seat.TestActivity");
//                intent.setComponent(componentName);
                    intent.putExtra("jss", "this from FUNUI");
                    intent.setDataAndType(Uri.parse("I'm from FunUI!"), "text/plain");
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case  R.id.action_settings:
                Toast.makeText(CombinaActivity.this, "I'm Menu Clicked", Toast.LENGTH_LONG).show();
                break;
            case  R.id.show_loading_activity:
                Intent i = new Intent(CombinaActivity.this, MainActivity.class);
                startActivity(i);
                break;
        }
        return true;
    }

    private void initData() {
        if(list == null) {
            list = new ArrayList<String>();
        }
        for (int i = 0; i < 100; i++){
            list.add("item-->" + i);
        }
    }

    private void initView() {
        //下拉是刷新组件设置
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        //设置样式刷新显示的位置
        mSwipeRefreshLayout.setProgressViewOffset(true, -20, 100);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.swiperefresh_color1, R.color.swiperefresh_color2, R.color.swiperefresh_color3, R.color.swiperefresh_color4);

        //RecyclerView 设置
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerAdapter = new RecyclerAdapter(CombinaActivity.this, list);
        mRecyclerAdapter.addOnItemClickListener(new RecyclerAdapter.OnItemClickListener() {//itemclick listener
            @Override
            public void onItemClick(ViewGroup group, View view, int position) {
                Intent intent = new Intent(CombinaActivity.this, GridActivity.class);
                startActivity(intent);
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); //设置RecyclerView布局方式线性布局
        mRecyclerView.setAdapter(mRecyclerAdapter);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new ItemDivider());

        //ViewPager Define
        mViewPager = (ViewPager) findViewById(R.id.toolbar_viewpager);
        mainPagerAdapter = new MainPagerAdapter(CombinaActivity.this, PAGE_RESOURCE);
        mViewPager.setAdapter(mainPagerAdapter);
        mViewPager.setCurrentItem(10 * PAGE_RESOURCE.length, true);

        appBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);

        menuListView = (ListView) findViewById(R.id.list_menu);
        DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) menuListView.getLayoutParams();
        params.width = (int)(CombinaActivity.this.getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.7);
        params.topMargin = getStatusBarHeight();
        menuListView.setLayoutParams(params);
        View headerView = LayoutInflater.from(this).inflate(R.layout.item_list_menu_title, null);

        CircleImageView circleImageView = (CircleImageView) headerView.findViewById(R.id.avatar);
        circleImageView.setOnClickListener(this);

        menuListView.addHeaderView(headerView);

        String[] strings = {"个人中心", "我的钱包", "我的相册", "设置"};
        menuListAdapter = new MenuListAdapter(CombinaActivity.this, strings);
        menuListView.setAdapter(menuListAdapter);

        drawerLayout = (DrawerLayout) findViewById(R.id.list_menu_drawer);
        toggle = new MyDrawerToggle(this, drawerLayout, 0, 1);
        drawerLayout.setDrawerListener(toggle);
        drawerLayout.post(new Runnable() {
            @Override
            public void run() {
                toggle.syncState();
            }
        });

        floatingActionButton = (FloatingActionButton) findViewById(R.id.float_action_button);
        floatingActionButton.setOnClickListener(this);
    }

    private void initViewAction() {
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                if (verticalOffset >= 0) {
                    mSwipeRefreshLayout.setEnabled(true);
                } else {
                    mSwipeRefreshLayout.setEnabled(false);
                }
            }
        });

        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //解决滑动冲突
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        mSwipeRefreshLayout.setEnabled(false);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        mSwipeRefreshLayout.setEnabled(true);
                        break;
                }
                //方案二
//                v.performClick(); //触发OnClick方法
//                mViewPager.getParent().requestDisallowInterceptTouchEvent(true); //防止父容器阻断子控件事件
                return false;
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), CombinaActivity.PAGE_RESOURCE[position % CombinaActivity.PAGE_RESOURCE.length]);
                Palette palette = Palette.from(bitmap).generate();
                Palette.Swatch swatch = palette.getVibrantSwatch();
                if (swatch == null) {
                    swatch = palette.getMutedSwatch();
                }
                int color = swatch.getRgb();
                collapsingToolbarLayout.setContentScrimColor(color);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onRefresh() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg = CombinaActivity.handler.obtainMessage();
                msg.obj = CombinaActivity.this;
                msg.what = 0;
                CombinaActivity.handler.sendMessage(msg);
            }
        }, 2000);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.float_action_button:
                Snackbar.make(v, "snackbar info", Snackbar.LENGTH_INDEFINITE).setAction("open", CombinaActivity.this).show();
                break;
            case R.id.snackbar_action:
                Intent intent = new Intent(CombinaActivity.this, RecyclerActivity.class);
                startActivity(intent);
                break;
            case R.id.avatar:
                Intent intent1 = new Intent(CombinaActivity.this, AvatarActivity.class);
                startActivity(intent1);
                break;
        }
    }

    class MyDrawerToggle extends ActionBarDrawerToggle {

        public MyDrawerToggle(Activity activity, DrawerLayout drawerLayout, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
            super(activity, drawerLayout, openDrawerContentDescRes, closeDrawerContentDescRes);
        }

        public MyDrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
            super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
//            super.onDrawerClosed(drawerView);
            invalidateOptionsMenu();
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            //super.onDrawerOpened(drawerView);
            CombinaActivity.this.invalidateOptionsMenu();
        }

    }
}
